package com.atXiao.food.rspcode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 响应返回码
 *
 * @author lixiaoxiao
 * @date 2023-11-23
 */
@Slf4j
public enum RspResultCode implements BaseResultCode {

    /**
     * 成功
     */
    REQUEST_SUCCESS("000000", "成功"),


    /**
     * 请求失败
     */
    REQUEST_ERROR("310000", "请求失败"),


    /**
     * 后台服务异常
     */
    SERVER_FAILURE("999999", "服务异常");


    /**
     * 返回编码
     */
    private final String code;

    /**
     * 返回端描述
     */
    private final String desc;

    /**
     * 返回码
     *
     * @param code
     * @param desc
     */
    RspResultCode(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    /**
     * 校验重复状态码
     *
     * @return true 校验通过、false 校验异常
     */
    public static Boolean checkRepeatCode() {
        ConcurrentHashMap<String, Integer> codeMap = new ConcurrentHashMap<>();
        for (RspResultCode value : RspResultCode.values()) {
            Integer code = codeMap.get(value.getCode());
            if (code == null) {
                codeMap.put(value.getCode(), 1);
            } else {
                codeMap.put(value.getCode(), code + 1);
            }
        }
        AtomicBoolean check = new AtomicBoolean(true);
        codeMap.forEach((k, v) -> {
            if (v.intValue() > 1) {
                log.error(">>>code重复：{}, 出现次数：{}", k, v);
                check.set(false);
            }
        });
        boolean isCheck = check.get();
        if (isCheck) {
            log.info(">>>code check success");
        }
        return check.get();
    }

    /**
     * 根据code获取对于msg
     *
     * @param code 状态码
     * @return msg 描述信息
     */
    public static RspResultCode getByCode(String code) {
        Assert.notNull(code, "code is null");
        for (RspResultCode codeEnum : RspResultCode.values()) {
            if (codeEnum.getCode().equals(code)) {
                return codeEnum;
            }
        }
        return null;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "RespCode{" + "code='" + code + '\'' + ", desc='" + desc + '\''
                + '}';
    }
}
